﻿var map = null;
var shapeLayer;
var lineLayer;
var leadsLayer;
var polyPoints = new Array();
var down = 0;
var X = 0, Y = 0;
var origin;
var MaxLat = 0;
var MinLat = 0;
var MaxLon = 0;
var MinLon = 0;
var menuLayer = null;
var IsNeedPostback = false;
var selectIndex = null;
var IsOrderPeriod = true;
var TeerQueue = new Array();
var ViewByAssignMent = false;
window.onload = function create_map() {
    hideHeaderDiv();
    if (window.screen.width == 1024) {
        document.getElementById("myMap1").className = "divAt1024";
    }
    else if (window.screen.width == 1280) {
        document.getElementById("myMap1").className = "divAt1280";
    }
    else {
        document.getElementById("myMap1").className = "divOthers";
    }
    map = new VEMap('myMap1');
    map.LoadMap();
    shapeLayer = new VEShapeLayer();
    map.AddShapeLayer(shapeLayer);
    map.EnableShapeDisplayThreshold(false);
    lineLayer = new VEShapeLayer();
    leadsLayer = new VEShapeLayer();
    map.AddShapeLayer(lineLayer);
    map.AddShapeLayer(leadsLayer);
    map.AttachEvent("onmouseup", MouseUpHandler);
    map.AttachEvent("onmousedown", MouseDownHandler);
    map.AttachEvent("onmousemove", MouseMoveHandler);
    PageMethods.Pin(CallBack);
    PageMethods.IsOrderPeriod(CallBackIsOrderPeriod);
    map.SetZoomLevel(7);
}

function hideHeaderDiv() {
    var current = document.getElementById("header");
    current.parentNode.removeChild(current);
    current = document.getElementById("topsection");
    current.parentNode.removeChild(current);
    current = document.getElementById("breadcrumb");
    current.parentNode.removeChild(current);
}

function showHistoryWindow1() {
    divmask1.style.visibility = 'visible';
    divmassage_box1.style.visibility = 'visible';
}

function CallBack(result) {
    TeerQueue = new Array();
    var serial = Sys.Serialization.JavaScriptSerializer;
    var info = serial.deserialize(result);
    selectIndex = document.getElementById("Select1").selectedIndex;
    if (info.length > 0) {
        MaxLat = info[0].Latitude;
        MinLat = info[0].Latitude;
        MaxLon = info[0].Longitude;
        MinLon = info[0].Longitude;
    }

    for (var i in info) {
        AddPushpin(info[i].Latitude, info[i].Longitude, info[i].LeadBlockCode, info[i].ZipName, info[i].City, info[i].Territory, info[i].ActiveLeadCount, info[i].LapsedLeadCount, info[i].NeighborLeadCount, info[i].BusinessLeadCount, info[i].IsOrdered, info[i].UserAssigned, info[i].ZipId, info[i].LastOrderDate);
        UpdateLatLon(info[i].Latitude, info[i].Longitude);
    }
    IsNeedPostback = false;

    var lat = (parseFloat(MaxLat) + parseFloat(MinLat)) / 2.0;
    var lon = (parseFloat(MaxLon) + parseFloat(MinLon)) / 2.0;
    var velatlon = new VELatLong(lat, lon);
    map.SetCenter(velatlon);
}

function CallBackleads(result) {
    var serial = Sys.Serialization.JavaScriptSerializer;
    var info = serial.deserialize(result);
    shapeLayer.Hide();
    leadsLayer.DeleteAllShapes();
    for (var i in info) {
        AddPushpinLeads(info[i].LeadId, info[i].SelPersonId, info[i].Zip, info[i].LeadBlockCode, info[i].Division, info[i].Market, info[i].Territory, info[i].CallType, info[i].LeadType, info[i].MdNumber, info[i].BirthDate, info[i].SequenceNumber, info[i].County, info[i].State, info[i].City, info[i].RawData, info[i].FirmName, info[i].LastName, info[i].FirstName, info[i].StreetAddress, info[i].LeadCity, info[i].LeadState, info[i].Telephone, info[i].SubSequenceNumber, info[i].Latitude, info[i].Longitude, info[i].SelDNC, info[i].PcLeadType, info[i].DncAfterDate, info[i].UserId);
        UpdateLatLon(info[i].Latitude, info[i].Longitude);
    }
    if (info.length > 0) {
        var lat = info[0].Latitude;
        var lon = info[0].Longitude;
        var velatlon = new VELatLong(lat, lon);
        map.SetCenterAndZoom(velatlon, 11);
    }

    leadsLayer.Show();

}

function CallBackIsOrderPeriod(result) {
    IsOrderPeriod = result;
}

function AddPushpin(x, y, leadBlock, zipCode, city, teer, active, lasped, neighbor, business, IsOrder, UserAssigned, ZipId, LastOrderDate) {
    var lat = x;
    var lon = y;
    var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, lon));
    shapeLayer.AddShape(shape);
    var info = 'Lead Block: ' + leadBlock + '<br>Zip Code:' + zipCode + '<br>City: ' + city + '<br>Territory: ' + teer + '<br>Active Count: ' + active + '<br>Lasped Count:' + lasped + '<br>Neighbor Count: ' + neighbor + '<br>Business Count: ' + business + '<br>' + 'Assignment Name:' + UserAssigned + '<br>' + 'Last date ordered:' + LastOrderDate + '<br>';
    var viewLeadText = '<br><a href="#" onclick="ViewLeads(' + "'" + ZipId + "'" + ')">View Leads</a>';
    if (IsOrder.toString() == 'true') {
        addActive(active, lasped, neighbor, business, teer);
        shape.SetCustomIcon(" <img src='../Content/Images/pin10.gif'/> ");
        shape.SetDescription(info + '<br><a href="#" onclick="RemoveFromCart(' + lat + ',' + lon + ",'" + leadBlock + "','" + zipCode + "','" + city + "','" + teer + "'," + active + "," + lasped + "," + neighbor + "," + business + ",'" + IsOrder + "','" + UserAssigned + "','" + shape.GetID() + "','" + ZipId + "','" + LastOrderDate + "'" + ');">Remove from cart.</a><br>' + viewLeadText);
    }
    else {
        shape.SetCustomIcon("<img src='../Content/Images/pin" + ReturnIconByTeer(teer) + ".gif'/> ");
        shape.SetDescription(info + '<br><a href="#" onclick="AddOrderedPushpin(' + lat + ',' + lon + ",'" + leadBlock + "','" + zipCode + "','" + city + "','" + teer + "'," + active + "," + lasped + "," + neighbor + "," + business + "," + IsOrder + ",'" + UserAssigned + "','" + shape.GetID() + "','" + ZipId + "','" + LastOrderDate + "'" + ');">Add to cart.</a><br>' + viewLeadText);
    }
    var LastOrder = '1';
    var lastMonthDate = document.getElementById("ctl00_DetailsContent_hideLastMonthDate").value; ;

    if (LastOrderDate != lastMonthDate) {
        LastOrder = '0';
    }
    shape.SetMoreInfoURL(ZipId + "|" + IsOrder + "|" + teer + "|" + shape.GetCustomIcon() + "|" + active + "|" + lasped + "|" + neighbor + "|" + business + "|" + LastOrder + "|" + UserAssigned);
    shape.SetPhotoURL('1'); //decide the shape hidden,1 show,0 hide ,2 hide by teer
}

function AddPushpinZipCodes(x, y, ZipName, teer, active, lasped, neighbor, business, UserId, IsOrdered) {
    var lat = x;
    var lon = y;
    var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, lon));
    shapeLayer.AddShape(shape);
    var info = '<br>Zip Name:' + ZipName + '<br>Territory: ' + teer + '<br>Active Count: ' + active + '<br>Lasped Count:' + lasped + '<br>Neighbor Count: ' + neighbor + '<br>Business Count: ' + business + '<br>';

    if (IsOrdered) {
        shape.SetCustomIcon("<img src='../Content/Images/pin10.gif'/> ");
        info += '<a href="#" onclick="ManageZipCodeToCart(1,' + lat + ',' + lon + ",'" + ZipName + "','" + teer + "'," + active + "," + lasped + "," + neighbor + "," + business + ",'" + UserId + "','" + shape.GetID() + "'" + ');">Remove from cart.</a>';
        // addActive(active,lasped,neighbor,business,teer);
    }
    else {
        shape.SetCustomIcon("<img src='../Content/Images/pin" + ReturnIconByTeer(teer) + ".gif'/> ");
        info += '<br><a href="#" onclick="ManageZipCodeToCart(0,' + lat + ',' + lon + ",'" + ZipName + "','" + teer + "'," + active + "," + lasped + "," + neighbor + "," + business + ",'" + UserId + "','" + shape.GetID() + "'" + ');">Add to cart.</a><br>';
    }
    shape.SetDescription(info);
    shape.SetMoreInfoURL(ZipName + "|" + teer + "|" + shape.GetCustomIcon() + "|" + active + "|" + lasped + "|" + neighbor + "|" + business + "|" + UserId + "|" + IsOrdered);
    shape.SetPhotoURL('1');
}

function AddPushpinLeads(LeadId, SelPersonId, Zip, LeadBlockCode, Division, Market, Territory, CallType, LeadType, MdNumber, BirthDate, SequenceNumber, County, State, City, RawData, FirmName, LastName, FirstName, StreetAddress, LeadCity, LeadState, Telephone, SubSequenceNumber, Latitude, Longitude, SelDNC, PcLeadType, DncAfterDate, UserId) {
    var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(Latitude, Longitude));
    leadsLayer.AddShape(shape);
    var info = "Zip+4:" + Zip + "<br>" + "LeadBlockCode:" + LeadBlockCode + "<br>" + "Division:" + Division + "<br>" + "Market:" + Market + "<br>" + "Territory:" + Territory + "<br>" + "CallType:" + CallType + "<br>" + "LeadType:" + LeadType + "<br>" + "BirthDate:" + BirthDate + "<br>" + "SequenceNumber:" + SequenceNumber + "<br>" + "FirmName:" + FirmName + "<br>" + "LastName:" + LastName + "<br>" + "FirstName:" + FirstName + "<br>" + "StreetAddress:" + StreetAddress + "<br>" + "City:" + LeadCity + "<br>" + "State:" + LeadState + "<br>" + "Telephone:" + Telephone + "<br>" + "SelDNC:" + SelDNC + "<br>" + "DncAfterDate:" + DncAfterDate + "<br>";
    info += '<br><a href="#" onclick="CloseLeadsView()" >Return</a>';
    shape.SetCustomIcon(" <img src='../Content/Images/pin3.gif'/> ");
    shape.SetDescription(info);
}
function ManageZipCodeToCart(OperateType, x, y, ZipName, teer, active, lasped, neighbor, business, UserId, ShapeID) {
    if (!IsOrderPeriod) {
        alert('Sorry,you can not operate now for the cut off date reached! ');
        return;
    }
    var shape = map.GetShapeByID(ShapeID);
    var paras = new Array();
    paras = shape.GetMoreInfoURL().spilt('|');
    var info = '<br>Zip Name:' + ZipName + '<br>Territory: ' + teer + '<br>Active Count: ' + active + '<br>Lasped Count:' + lasped + '<br>Neighbor Count: ' + neighbor + '<br>Business Count: ' + business + '<br>';
    if (OperateType == 0) {
        if (paras[8] == '0') {
            shape.SetCustomIcon(" <img src='../Content/Images/pin10.gif'/> ");
            info += '<a href="#" onclick="ManageZipCodeToCart(1,' + lat + ',' + lon + ",'" + ZipName + "','" + teer + "'," + active + "," + lasped + "," + neighbor + "," + business + ",'" + UserId + "','" + shape.GetID() + "'" + ');SubActive(' + active + ',' + lasped + ',' + neighbor + ',' + business + ',' + teer + ')">Remove from cart.</a>';
            shape.SetDescription(info);
            shape.SetMoreInfoURL(shape.GetMoreInfoURL().replace('false', 'true'));
            addActive(active, lasped, neighbor, business, teer);
            PageMethods.ManagerZipCodeToCart(ZipName, OperateType);
        }
    }
    else {
        if (paras[8] == '1') {
            shape.SetCustomIcon("<img src='../Content/Images/pin" + ReturnIconInArray(teer) + ".gif'/> ");
            info += '<br><a href="#" onclick="ManageZipCodeToCart(0,' + lat + ',' + lon + ",'" + ZipName + "','" + teer + "'," + active + "," + lasped + "," + neighbor + "," + business + ",'" + UserId + "','" + shape.GetID() + "'" + ');addActive(' + active + ',' + lasped + ',' + neighbor + ',' + business + ',' + teer + ')">Add to cart.</a><br>';
            shape.SetDescription(info);
            shape.SetMoreInfoURL(shape.GetMoreInfoURL().replace('true', 'false'));
            SubActive(active, lasped, neighbor, business, teer);
            PageMethods.ManagerZipCodeToCart(ZipName, OperateType);
        }
    }
}

function AddOrderedPushpin(x, y, leadBlock, zipCode, city, teer, active, lasped, neighbor, business, IsOrder, UserAssigned, shapeID, ZipId, IsLastOrdered) {
    if (!IsOrderPeriod) {
        alert('Sorry,you can not operate now for the cut off date reached! ');
        return;
    }
    var shape = map.GetShapeByID(shapeID);
    if (shape.GetMoreInfoURL().indexOf("false") != -1) //confirm it had ordered .
    {
        var lat = x;
        var lon = y;
        shape.SetCustomIcon(" <img src='../Content/Images/pin10.gif'/> ");
        var info = 'Lead Block: ' + leadBlock + '<br>Zip Code:' + zipCode + '<br>City: ' + city + '<br>Terr: ' + teer + '<br>Active Count: ' + active + '<br>Lasped Count:' + lasped + '<br>Neighbor Count: ' + neighbor + '<br>Business Count: ' + business + '<br>' + 'Assignment Name:' + UserAssigned + '<br>' + 'Last date ordered:' + IsLastOrdered + '<br>';
        var viewLeadText = '<br><a href="#" onclick="ViewLeads(' + "'" + ZipId + "'" + ')">View Leads</a>';
        shape.SetDescription(info + '<br><a href="#" onclick="RemoveFromCart(' + lat + ',' + lon + ",'" + leadBlock + "','" + zipCode + "','" + city + "','" + teer + "'," + active + "," + lasped + "," + neighbor + "," + business + ",'" + IsOrder + "','" + UserAssigned + "','" + shapeID + "','" + ZipId + "','" + IsLastOrdered + "'" + ');">Remove from cart.</a>' + viewLeadText);
        shape.SetMoreInfoURL(shape.GetMoreInfoURL().replace('false', 'true'));
        PageMethods.ManagerZipToCart(ZipId, '0');
        addActive(active, lasped, neighbor, business, teer);
    }
}

function RemoveFromCart(x, y, leadBlock, zipCode, city, teer, active, lasped, neighbor, business, IsOrder, UserAssigned, shapeID, ZipId, IsLastOrdered) {
    if (!IsOrderPeriod) {
        alert('Sorry,you can not operate now for the cut off date reached! ');
        return;
    }
    if (shapeID != null) {
        var shape = map.GetShapeByID(shapeID);
        if (shape.GetMoreInfoURL().indexOf("true") != -1)  //have not ordered yet.
        {
            var info = 'Lead Block: ' + leadBlock + '<br>Zip Code:' + zipCode + '<br>City: ' + city + '<br>Terr: ' + teer + '<br>Active Count: ' + active + '<br>Lasped Count:' + lasped + '<br>Neighbor Count: ' + neighbor + '<br>Business Count: ' + business + '<br>' + 'Assignment Name:' + UserAssigned + '<br>' + 'Last date ordered:' + IsLastOrdered + '<br>';
            var viewLeadText = '<br><a href="#" onclick="ViewLeads(' + "'" + ZipId + "'" + ')">View Leads</a>';
            shape.SetDescription(info + '<br><a href="#" onclick="AddOrderedPushpin(' + x + ',' + y + ",'" + leadBlock + "','" + zipCode + "','" + city + "','" + teer + "'," + active + "," + lasped + "," + neighbor + "," + business + "," + IsOrder + ",'" + UserAssigned + "','" + shapeID + "'," + ZipId + ",'" + IsLastOrdered + "'" + ');">Add to cart.</a>' + viewLeadText);
            shape.SetCustomIcon("<img src='../Content/Images/pin" + ReturnIconInArray(teer) + ".gif'/> ");
            SubActive(active, lasped, neighbor, business, teer);
            PageMethods.ManagerZipToCart(ZipId, '1');
            shape.SetMoreInfoURL(shape.GetMoreInfoURL().replace('true', 'false'));
        }
    }
}


function addActive(A, L, N, B, Teer) {
    var lbneighbor = document.getElementById("ctl00_InfoContent_lbNeighborLead");
    var lbactive = document.getElementById("ctl00_InfoContent_lbActiveLead");
    var lbbussiness = document.getElementById("ctl00_InfoContent_lbBussinessLead");
    var lblapse = document.getElementById("ctl00_InfoContent_lbLapseLead");
    var lbsum = document.getElementById("ctl00_InfoContent_lbCartAgent");
    var lbremain = document.getElementById("ctl00_InfoContent_lblRemain");
    var lbtotal = document.getElementById("lbTtotal");

    var teer = document.getElementById("ctl00_InfoContent_drpTeer").options[document.getElementById("ctl00_InfoContent_drpTeer").selectedIndex].value;
    var teerlbneighbor = document.getElementById("ctl00_InfoContent_TeerlbNeighborLead");
    var teerlbactive = document.getElementById("ctl00_InfoContent_TeerlbActiveLead");
    var teerlbbussiness = document.getElementById("ctl00_InfoContent_TeerlbBussinessLead");
    var teerlblapse = document.getElementById("ctl00_InfoContent_TeerlbLapseLead");
    var teerlbtotal = document.getElementById("ctl00_InfoContent_TeerlbTotal");

    if (lbremain.innerHTML == '0') {
        lbremain.innerHTML = lbtotal.innerHTML;
    }
    lbremain.innerHTML = lbremain.innerHTML - parseInt(A) - parseInt(L);
    lbactive.innerHTML = parseInt(lbactive.innerHTML) + parseInt(A);
    lbbussiness.innerHTML = parseInt(lbbussiness.innerHTML) + parseInt(B);
    lblapse.innerHTML = parseInt(lblapse.innerHTML) + parseInt(L);
    lbneighbor.innerHTML = parseInt(lbneighbor.innerHTML) + parseInt(N);
    lbsum.innerHTML = parseInt(lbactive.innerHTML) + parseInt(lblapse.innerHTML);

    if (teer == Teer) {
        teerlbactive.innerHTML = parseInt(teerlbactive.innerHTML) + parseInt(A);
        teerlblapse.innerHTML = parseInt(teerlblapse.innerHTML) + parseInt(L);
        teerlbneighbor.innerHTML = parseInt(teerlbneighbor.innerHTML) + parseInt(N);
        teerlbbussiness.innerHTML = parseInt(teerlbbussiness.innerHTML) + parseInt(B);
        teerlbtotal.innerHTML = parseInt(teerlbtotal.innerHTML) + parseInt(A) + parseInt(L) + parseInt(N) + parseInt(B);
    }
}

function SubActive(A, L, N, B, Teer) {
    var lbneighbor = document.getElementById("ctl00_InfoContent_lbNeighborLead");
    var lbactive = document.getElementById("ctl00_InfoContent_lbActiveLead");
    var lbbussiness = document.getElementById("ctl00_InfoContent_lbBussinessLead");
    var lblapse = document.getElementById("ctl00_InfoContent_lbLapseLead");
    var lbsum = document.getElementById("ctl00_InfoContent_lbCartAgent");
    var lbremain = document.getElementById("ctl00_InfoContent_lblRemain");
    var lbtotal = document.getElementById("lbTtotal");

    var teer = document.getElementById("ctl00_InfoContent_drpTeer").options[document.getElementById("ctl00_InfoContent_drpTeer").selectedIndex].value;
    var teerlbneighbor = document.getElementById("ctl00_InfoContent_TeerlbNeighborLead");
    var teerlbactive = document.getElementById("ctl00_InfoContent_TeerlbActiveLead");
    var teerlbbussiness = document.getElementById("ctl00_InfoContent_TeerlbBussinessLead");
    var teerlblapse = document.getElementById("ctl00_InfoContent_TeerlbLapseLead");
    var teerlbtotal = document.getElementById("ctl00_InfoContent_TeerlbTotal");

    if (lbremain.innerHTML == '0') {
        lbremain.innerHTML = lbtotal.innerHTML;
    }
    lbremain.innerHTML = parseInt(lbremain.innerHTML) + parseInt(A) + parseInt(L);
    lbactive.innerHTML = parseInt(lbactive.innerHTML) - parseInt(A);
    lbbussiness.innerHTML = parseInt(lbbussiness.innerHTML) - parseInt(B);
    lblapse.innerHTML = parseInt(lblapse.innerHTML) - parseInt(L);
    lbneighbor.innerHTML = parseInt(lbneighbor.innerHTML) - parseInt(N);
    lbsum.innerHTML = parseInt(lbsum.innerHTML) - parseInt(A) - parseInt(L);
    if (teer == Teer) {
        teerlbactive.innerHTML = parseInt(teerlbactive.innerHTML) - parseInt(A);
        teerlblapse.innerHTML = parseInt(teerlblapse.innerHTML) - parseInt(L);
        teerlbneighbor.innerHTML = parseInt(teerlbneighbor.innerHTML) - parseInt(N);
        teerlbbussiness.innerHTML = parseInt(teerlbbussiness.innerHTML) - parseInt(B);
        teerlbtotal.innerHTML = parseInt(teerlbtotal.innerHTML) - parseInt(A) - parseInt(L) - parseInt(N) - parseInt(B);
    }
}

function hideEachShape() {
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        shape.Hide();
    }
}

function drawPolygon() {
    //remove the polygon that is on the map

    lineLayer.DeleteAllShapes();

    //draw polyline if there is only two points in the array
    if (polyPoints.length < 3) {
        var polygon = new VEShape(VEShapeType.Polyline, polyPoints);
    }
    else {
        //create a new polygon
        var polygon = new VEShape(VEShapeType.Polygon, polyPoints);
    }
    polygon.SetZIndex(shapeLayer.GetShapeCount() + 99);
    polygon.HideIcon();

    //draw the new polygon on the map
    lineLayer.AddShape(polygon);

}


function polygonDescrption() {
    var counter = 0;
    var ordered = 0;
    var unorder = 0;
    var a = 0;
    var l = 0;
    var n = 0;
    var b = 0;
    var str = new Array();
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        var latlong = shape.GetPoints()[0];
        var lat = latlong.Latitude;
        var lon = latlong.Longitude;
        var IfHidden = shape.GetPhotoURL();

        if (IfHidden != '0' && pointInPolygon(polyPoints, lat, lon)) {
            var icon = shape.GetCustomIcon();
            if (icon.substr(icon.lastIndexOf('.') - 2, 2) == '10')  //Decide if order,because the order pushpin's icon is pin10.gif
            {
                ordered++;
            }
            else {
                unorder++;
            }
        }


        // alert('ok');
        if (!IsNeedPostback && pointInPolygon(polyPoints, lat, lon)) {
            str = shape.GetMoreInfoURL().split('|');
            a = a + parseInt(str[4]);
            l = l + parseInt(str[5]);
            n = n + parseInt(str[6]);
            b = b + parseInt(str[7]);
        }
    }
    var info = '';
    if (!IsNeedPostback) {
        info = "Your totals so far are:<br>&nbsp;&nbsp;&nbsp;Acitve:" + a + "<br>&nbsp;&nbsp;&nbsp;Lasped:" + l + "<br>&nbsp;&nbsp;&nbsp;Neighbor:" + n + "<br>&nbsp;&nbsp;&nbsp;Business:" + b;
        info += "<br>&nbsp;&nbsp;&nbsp;<a href='#' onclick='polygonManagerToCart(0);'  >Add to cart. </a>";
        info += "<br>&nbsp;&nbsp;&nbsp; <a href='#' onclick='polygonManagerToCart(1);'  >Remove from cart. </a>";
        info += "<br>&nbsp;&nbsp;&nbsp;<a href='#' onclick='polygonAssign();'  >Assign Agent</a>";
    }
    else {
        info = "<br>&nbsp;&nbsp;&nbsp;<a href='#' onclick='polygonManagerZipCodeToCart(0);'  >Add to cart. </a>";
        info += "<br>&nbsp;&nbsp;&nbsp; <a href='#' onclick='polygonManagerZipCodeToCart(1);'  >Remove from cart. </a>";
    }
    lineLayer.DeleteAllShapes();
    if (polyPoints.length < 3) {
        var polygon = new VEShape(VEShapeType.Polyline, polyPoints);
    }
    else {
        var polygon = new VEShape(VEShapeType.Polygon, polyPoints);
    }

    if (!(ordered == 0 && unorder == 0)) {
        var menuLayer1 = document.getElementById('divPolygon');
        menuLayer1.style.position = "absolute";
        menuLayer1.style.top = window.event.clientY;
        menuLayer1.style.left = window.event.clientX;
        menuLayer1.style.width = "160px";
        menuLayer1.style.height = "170px";
        menuLayer1.style.zIndex = shapeLayer.GetShapeCount() + 100;
        // menuLayer1.style.backgroundColor = "white";
        //menuLayer1.style.borderTopWidth="1px";
        var contentmenu = document.getElementById('PolyMenuContent');
        contentmenu.innerHTML = info;
        menuLayer1.style.visibility = 'visible';
    }
    polygon.HideIcon();
    lineLayer.AddShape(polygon);
    menuLayer = true;
}

function polygonAssign() {
    divmassage_box1.style.visibility = 'visible';
    divmask1.style.visibility = 'visible';
}
function polygonManagerToCart(operate) {
    if (!IsOrderPeriod) {
        alert('Sorry,you can not operate now for the cut off date reached! ');
        return;
    }
    var counter = 0;
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        var latlong = shape.GetPoints()[0];
        var lat = latlong.Latitude;
        var lon = latlong.Longitude;
        var str = new Array();
        var IfHidden = shape.GetPhotoURL();

        if (IfHidden != '0' && pointInPolygon(polyPoints, lat, lon)) {
            var description = shape.GetDescription();
            str = shape.GetMoreInfoURL().split('|');
            var teer = str[2];

            if (operate == '0' && str[1] == 'false') {
                description = description.replace('AddOrderedPushpin', 'RemoveFromCart');
                description = description.replace('Add to cart', 'Remove from cart');
                //description=description.replace('addActive','SubActive');
                PageMethods.ManagerZipToCart(str[0], '0');
                shape.SetCustomIcon(" <img src='../Content/Images/pin10.gif'/> ");
                addActive(str[4], str[5], str[6], str[7], str[2]);
                shape.SetMoreInfoURL(shape.GetMoreInfoURL().replace('false', 'true'));
            }
            if (operate == '1' && str[1] == 'true') {
                description = description.replace('RemoveFromCart', 'AddOrderedPushpin');
                description = description.replace('Remove from cart', 'Add to cart');
                //description=description.replace('SubActive','addActive');
                PageMethods.ManagerZipToCart(str[0], '1');
                shape.SetCustomIcon("<img src='../Content/Images/pin" + ReturnIconInArray(teer) + ".gif'/> ");
                SubActive(str[4], str[5], str[6], str[7], str[2]);
                shape.SetMoreInfoURL(shape.GetMoreInfoURL().replace('true', 'false'));
                if (menuLayer != null) {
                    lineLayer.DeleteAllShapes();
                    var menuLayer1 = document.getElementById('divPolygon');
                    menuLayer1.style.visibility = 'hidden';
                    menuLayer = null;
                }
            }
            shape.SetDescription(description);
        }
    }
}

function polygonManagerZipCodeToCart(operate) {
    if (!IsOrderPeriod) {
        alert('Sorry,you can not operate now for the cut off date reached! ');
        return;
    }
    var counter = 0;
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        var latlong = shape.GetPoints()[0];
        var lat = latlong.Latitude;
        var lon = latlong.Longitude;
        var str = new Array();
        if (pointInPolygon(polyPoints, lat, lon)) {
            var description = shape.GetDescription();
            str = shape.GetMoreInfoURL().split('|');
            var teer = str[1];
            if (operate == '0' && str[8] == 'false') {
                description = description.replace('ManageZipCodeToCart(0', 'ManageZipCodeToCart(1');
                description = description.replace('Add to cart', 'Remove from cart');
                //description=description.replace('addActive','SubActive');
                shape.SetCustomIcon("<img src='../Content/Images/pin10.gif'/> ");
                PageMethods.ManagerZipCodeToCart(str[0], operate);
                addActive(str[3], str[4], str[5], str[6], str[1]);
                shape.SetMoreInfoURL(shape.GetMoreInfoURL().replace('false', 'true'));
            }
            if (operate == '1' && str[8] == 'true') {
                description = description.replace('ManageZipCodeToCart(1', 'ManageZipCodeToCart(0');
                description = description.replace('Remove from cart', 'Add to cart');
                // description=description.replace('SubActive','addActive');
                shape.SetCustomIcon("<img src='../Content/Images/pin" + teer.substring(teer.length - 1) + ".gif'/> ");
                SubActive(str[3], str[4], str[5], str[6], str[1]);
                PageMethods.ManagerZipCodeToCart(str[0], operate);
                shape.SetMoreInfoURL(shape.GetMoreInfoURL().replace('true', 'false'));
                if (menuLayer != null) {
                    lineLayer.DeleteAllShapes();
                    var menuLayer1 = document.getElementById('divPolygon');
                    menuLayer1.style.visibility = 'hidden';
                    menuLayer = null;
                }
            }
            shape.SetDescription(description);
        }
    }
}

function pointInPolygon(points, lat, lon) {
    var i;
    var j = points.length - 1;
    var inPoly = false;

    for (i = 0; i < points.length; i++) {

        if (points[i].Longitude < lon && points[j].Longitude >= lon || points[j].Longitude < lon && points[i].Longitude >= lon) {
            if (points[i].Latitude + (lon - points[i].Longitude) / (points[j].Longitude - points[i].Longitude) * (points[j].Latitude - points[i].Latitude) < lat) {
                inPoly = !inPoly;
            }
        }
        j = i;
    }

    return inPoly;
}

function MouseUpHandler(e) {
    if (e.leftMouseButton) {
        if (down == 1) {
            down = 0;
            polyPoints.push(origin);
            polygonDescrption();
            X = 0;
            Y = 0;
        }
        else {
            var menuLayer1 = document.getElementById('divPolygon');
            if (menuLayer != null) {
                menuLayer1.style.visibility = 'hidden';
                lineLayer.DeleteAllShapes();
                menuLayer = null;
            }
        }
    }
}

function MouseDownHandler(e) {
    if (shapeLayer.IsVisible()) {
        if (e.rightMouseButton) {
            X = e.mapX;
            Y = e.mapY;
            var point = map.PixelToLatLong(new VEPixel(X, Y));
            if (down == 0) {
                //intialize the map and variables.                       
                lineLayer.DeleteAllShapes();
                if (menuLayer != null) {
                    var menuLayer1 = document.getElementById('divPolygon');
                    menuLayer1.style.visibility = 'hidden';
                    menuLayer = null;
                }
                polyPoints = new Array(0);
                origin = point;
                polyPoints.push(origin);
                down = 1;
            }
            //add the new point to the array
            polyPoints.push(point);
            menuKey = true;
            return true;
        }
    }
}

function MouseMoveHandler(e) {
    if (down == 1) {
        var x = e.mapX;
        var y = e.mapY;

        var dx = Math.abs(X) - Math.abs(x);
        var dy = Math.abs(Y) - Math.abs(y);

        //do not want to redraw polygon unless we move a significant amount
        if (Math.abs(dx) > 5 || Math.abs(dy) > 5) {
            var latlong = map.PixelToLatLong(new VEPixel(x, y));
            polyPoints.pop();
            polyPoints.push(latlong);
            drawPolygon();
        }
    }
}

function UnSelectAll() {
    if (confirm("Are you sure you are going to removed all leads from cart ?")) {
        for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
            var shape = shapeLayer.GetShapeByIndex(i);
            var latlong = shape.GetPoints()[0];
            var lat = latlong.Latitude;
            var lon = latlong.Longitude;
            var str = new Array();
            str = shape.GetMoreInfoURL().split('|');
            var teer;
            var isOrder;
            if (!IsNeedPostback) {
                teer = str[2];
                isOrder = str[1];
            }
            else {
                teer = str[1];
                isOrder = str[8];
            }
            if (isOrder == 'true') {
                var description = shape.GetDescription();
                if (!IsNeedPostback) {
                    description = description.replace('RemoveFromCart', 'AddOrderedPushpin');
                    description = description.replace('Remove from cart', 'Add to cart');
                    PageMethods.ManagerZipToCart(str[0], '1');
                    shape.SetCustomIcon("<img src='../Content/Images/pin" + ReturnIconInArray(teer) + ".gif'/> ");
                    shape.SetMoreInfoURL(shape.GetMoreInfoURL().replace('true', 'false'));
                }
                else {
                    description = description.replace('ManageZipCodeToCart(1', 'ManageZipCodeToCart(0');
                    description = description.replace('Remove from cart', 'Add to cart');
                    shape.SetCustomIcon("<img src='../Content/Images/pin" + ReturnIconInArray(teer) + ".gif'/> ");
                    shape.SetMoreInfoURL(shape.GetMoreInfoURL().replace('true', 'false'));
                    PageMethods.ManagerZipCodeToCart(str[0], 1);
                }
                clearSummary();
            }
        }
    }
}

function ViewLeads(ZIPId) {
    PageMethods.LeadsPin(ZIPId, CallBackleads);
}

function FilterLeads() {
    if (!shapeLayer.IsVisible()) {
        map.SetZoomLevel(7);
        leadsLayer.Hide();
        shapeLayer.Show();
    }
    ShowAllLead();
    var selectTeer = document.getElementById("ctl00_DetailsContent_drpTeer1").options[document.getElementById("ctl00_DetailsContent_drpTeer1").selectedIndex].value;
    var SelectZip = document.getElementById("ctl00_DetailsContent_drpZip").options[document.getElementById("ctl00_DetailsContent_drpZip").selectedIndex].value;
    var SelectCity = document.getElementById("ctl00_DetailsContent_drpCity").options[document.getElementById("ctl00_DetailsContent_drpCity").selectedIndex].value;
    SelectCity = " " + SelectCity.replace(/(^s*)|(s*$)/g, "");
    var IsIntiLatLon = false;
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        str = shape.GetMoreInfoURL().split('|');
        switch (selectIndex) {
            case 0:
                {
                    if (str[1] == 'false') {
                        shape.Hide();
                        shape.SetPhotoURL('0');
                        continue;
                    }
                    break;
                }
            case 1:
                {
                    shape.Show();
                    shape.SetPhotoURL('1');
                    break;
                }
            case 2:
                {
                    var assign = str[9];
                    assign = assign.replace(/(^\s*)|(\s*$)/g, "");
                    if (assign == 'null' || assign == '') {
                        shape.Hide();
                        shape.SetPhotoURL('0');
                        continue;
                    }
                    else if (assign != 'null' && assign !== '') {
                        shape.Show();
                        shape.SetPhotoURL('1');
                        shape.SetCustomIcon("<img src='../Content/Images/pin" + SubLastChar(ReturnIconInArray(str[9])) + ".gif'/> ");
                    }
                    break;
                }
            case 3:
                {
                    if (str[8] == '0') {
                        shape.Hide();
                        shape.SetPhotoURL('0');
                        continue;
                    }
                    else {
                        shape.Show();
                        shape.SetPhotoURL('1');
                    }
                    break;
                }
        }

        if (selectTeer != 0 && selectTeer != str[2]) {
            shape.Hide();
            shape.SetPhotoURL('0');
            continue;
        }

        if (SelectZip != 0) {
            var description = shape.GetDescription();
            var leadZip = getMiddeStr(description, "Zip Code:", "<br>City:");
            if (SelectZip != leadZip) {
                shape.Hide();
                shape.SetPhotoURL('0');
                continue;
            }
        }

        if (SelectCity != 0) {
            var description = shape.GetDescription();
            var leadCity = getMiddeStr(description, "City:", "<br>Territory:");
            if (SelectCity.substring(0, 4) != leadCity.substring(0, 4)) {
                shape.Hide();
                shape.SetPhotoURL('0');
                continue;
            }
        }
        if (shape.GetPhotoURL() != '0') {
            var velatlon = shape.GetPoints();
            if (!IsIntiLatLon) {
                MaxLat = velatlon[0].Latitude;
                MinLat = velatlon[0].Latitude;
                MaxLon = velatlon[0].Longitude;
                MinLon = velatlon[0].Longitude;
                IsIntiLatLon = true;
            }
            UpdateLatLon(velatlon[0].Latitude, velatlon[0].Longitude);
        }

    }

    if (IsIntiLatLon) {
        var lat = (parseFloat(MaxLat) + parseFloat(MinLat)) / 2.0;
        var lon = (parseFloat(MaxLon) + parseFloat(MinLon)) / 2.0;
        velatlon = new VELatLong(lat, lon);
        if (SelectCity == 0 && selectTeer == 0 && SelectZip == 0) {
            map.SetCenterAndZoom(velatlon, 7);
        }
        else {
            map.SetCenterAndZoom(velatlon, 9);
        }
    }
}

function ResetPushpin() {
    selectIndex = document.getElementById("Select1").selectedIndex;
    if (ViewByAssignMent) {
        for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
            var shape = shapeLayer.GetShapeByIndex(i);
            str = shape.GetMoreInfoURL().split('|');
            if (shape.GetPhotoURL() != '2') {
                shape.Show();
                shape.SetPhotoURL('1');
                if (str[1] != 'true') {
                    shape.SetCustomIcon("<img src='../Content/Images/pin" + ReturnIconInArray(str[2]) + ".gif'/> ");
                }
                else {
                    shape.SetCustomIcon(" <img src='../Content/Images/pin10.gif'/> ");
                }
            }
        }
        ViewByAssignMent = false;
    }
    if (selectIndex == 2) {
        for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
            var shape = shapeLayer.GetShapeByIndex(i);
            str = shape.GetMoreInfoURL().split('|');
            var assign = str[9];
            assign = assign.replace(/(^\s*)|(\s*$)/g, "");
            if (assign != 'null' && assign !== '') {
                shape.Show();
                shape.SetPhotoURL('1');
                shape.SetCustomIcon("<img src='../Content/Images/pin" + SubLastChar(ReturnIconInArray(str[9])) + ".gif'/> ");
            }
        }
        ViewByAssignMent = true;
    }
}

function clearSummary() {
    var lbneighbor = document.getElementById("ctl00_InfoContent_lbNeighborLead");
    var lbactive = document.getElementById("ctl00_InfoContent_lbActiveLead");
    var lbbussiness = document.getElementById("ctl00_InfoContent_lbBussinessLead");
    var lblapse = document.getElementById("ctl00_InfoContent_lbLapseLead");
    var lbsum = document.getElementById("ctl00_InfoContent_lbCartAgent");
    var lbremain = document.getElementById("ctl00_InfoContent_lblRemain");

    var teer = document.getElementById("ctl00_InfoContent_drpTeer").options[document.getElementById("ctl00_InfoContent_drpTeer").selectedIndex].value;
    var teerlbneighbor = document.getElementById("ctl00_InfoContent_TeerlbNeighborLead");
    var teerlbactive = document.getElementById("ctl00_InfoContent_TeerlbActiveLead");
    var teerlbbussiness = document.getElementById("ctl00_InfoContent_TeerlbBussinessLead");
    var teerlblapse = document.getElementById("ctl00_InfoContent_TeerlbLapseLead");
    var teerlbtotal = document.getElementById("ctl00_InfoContent_TeerlbTotal");
    lbneighbor.innerHTML = '0';
    lbactive.innerHTML = '0';
    lbbussiness.innerHTML = '0';
    lblapse.innerHTML = '0';
    lbsum.innerHTML = '0';
    lbremain.innerHTML = '0';
    teerlbactive.innerHTML = '0';
    teerlbbussiness.innerHTML = '0';
    teerlbneighbor.innerHTML = '0';
    teerlblapse.innerHTML = '0';
    teerlbtotal.innerHTML = '0';
}

function addActiveTeer() {
    var teer = document.getElementById("ctl00_InfoContent_drpTeer").options[document.getElementById("ctl00_InfoContent_drpTeer").selectedIndex].value;
    var lbneighbor = document.getElementById("ctl00_InfoContent_TeerlbNeighborLead");
    var lbactive = document.getElementById("ctl00_InfoContent_TeerlbActiveLead");
    var lbbussiness = document.getElementById("ctl00_InfoContent_TeerlbBussinessLead");
    var lblapse = document.getElementById("ctl00_InfoContent_TeerlbLapseLead");
    var lbtotal = document.getElementById("ctl00_InfoContent_TeerlbTotal");
    var active = 0;
    var bussiness = 0;
    var neigh = 0;
    var lapsed = 0;
    var sum = 0;
    if (!IsNeedPostback) {
        for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
            var shape = shapeLayer.GetShapeByIndex(i);
            var str = new Array();
            str = shape.GetMoreInfoURL().split('|');
            var currentTeer = str[2];
            if (str[1] == 'true' && teer == currentTeer) {
                active += parseInt(str[4]);
                bussiness += parseInt(str[7]);
                neigh += parseInt(str[6]);
                lapsed += parseInt(str[5]);
            }
        }
    }
    else {
        for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
            var shape = shapeLayer.GetShapeByIndex(i);
            var str = new Array();
            str = shape.GetMoreInfoURL().split('|');
            var currentTeer = str[1];
            if (str[8] == 'true' && teer == currentTeer) {
                active += parseInt(str[3]);
                bussiness += parseInt(str[6]);
                neigh += parseInt(str[5]);
                lapsed += parseInt(str[4]);
            }
        }
    }
    sum = active + bussiness + neigh + lapsed;
    lbactive.innerHTML = active;
    lbbussiness.innerHTML = bussiness;
    lbneighbor.innerHTML = neigh;
    lblapse.innerHTML = lapsed;
    lbtotal.innerHTML = sum;
}

function polygonAssignZips(agentID)  //if agentID is 0,then clear assign,others assgin to agenID
{
    divmassage_box1.style.visibility = 'hidden';
    divmask1.style.visibility = 'hidden';
    var agentName = document.getElementById("ctl00_DetailsContent_drpAssignment").options[document.getElementById("ctl00_DetailsContent_drpAssignment").selectedIndex].text;
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        var latlong = shape.GetPoints()[0];
        var lat = latlong.Latitude;
        var lon = latlong.Longitude;
        if (pointInPolygon(polyPoints, lat, lon)) {
            var str = new Array();
            str = shape.GetMoreInfoURL().split('|');
            if (agentID != '0') {
                PageMethods.AssignZips(str[0], agentID);
                var description = shape.GetDescription();
                var description1 = description.substring(description.indexOf("Assign Agent:") + 13);
                description = description.substring(0, description.indexOf("Assign Agent:") + 13) + agentName + description1.substring(description1.indexOf("<br>"));
                shape.SetDescription(description);
            }
        }
    }
    var drpAssign = document.getElementById("ctl00_DetailsContent_drpAssignment");
    drpAssign.selectedIndex = 0;
}

function ShowAssignDiv() {
    var menuLayer1 = document.getElementById('divPolygon');
    menuLayer1.style.visibility = 'hidden';
    lineLayer.DeleteAllShapes();
    menuLayer = null;
    polygonAssignZips(document.getElementById('ctl00_DetailsContent_drpAssignment').options[document.getElementById('ctl00_DetailsContent_drpAssignment').selectedIndex].value);
    divmassage_box1.style.visibility = 'hidden';
    divmask1.style.visibility = 'hidden';
}

function ReturnIconByTeer(teer) {
    if (TeerQueue.length != 0) {
        if (TeerQueue[TeerQueue.length - 1] != teer) {
            TeerQueue.push(teer);
        }
        return TeerQueue.length - 1;
    }
    else {
        TeerQueue.push(teer);
        return 0;
    }
}

function ReturnIconInArray(teer) {
    for (var i = 0; i < TeerQueue.length; i++) {
        if (TeerQueue[i] == teer) {
            return i;
        }
    }
    TeerQueue.push(teer);
    return TeerQueue.length - 1;
}

function SubLastChar(str) {
    str = String(str);
    str = str.charAt(str.length - 1);
    return str;
}

function UpdateLatLon(lat, lon) {
    if (lat > MaxLat) {
        MaxLat = lat;
    }
    else if (lat < MinLat) {
        MinLat = lat;
    }

    if (lon > MaxLon) {
        MaxLon = lon;
    }
    else if (lon < MinLon) {
        MinLon = lon;
    }

}

function ShowAllLead() {
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        shape.SetPhotoURL('1');
        shape.Show();
    }
}
function getMiddeStr(str, startStr, endStr) {
    var start = str.indexOf(startStr) + startStr.length;
    var end = str.indexOf(endStr);
    var returnStr = str.substring(start, end);
    returnStr.replace(/(^s*)|(s*$)/g, "");
    return returnStr;
}

function CloseLeadsView() {
    if (!shapeLayer.IsVisible()) {
        leadsLayer.DeleteAllShapes();
        leadsLayer.Hide();
        shapeLayer.Show();
        IsIntiLatLon = false;
        for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
            var shape = shapeLayer.GetShapeByIndex(i);
            if (shape.GetPhotoURL() != '0') {
                var velatlon = shape.GetPoints();
                if (!IsIntiLatLon) {
                    MaxLat = velatlon[0].Latitude;
                    MinLat = velatlon[0].Latitude;
                    MaxLon = velatlon[0].Longitude;
                    MinLon = velatlon[0].Longitude;
                    IsIntiLatLon = true;
                }
                UpdateLatLon(velatlon[0].Latitude, velatlon[0].Longitude);
            }
        }
        var lat = (parseFloat(MaxLat) + parseFloat(MinLat)) / 2.0;
        var lon = (parseFloat(MaxLon) + parseFloat(MinLon)) / 2.0;
        velatlon = new VELatLong(lat, lon);
        map.SetCenterAndZoom(velatlon, 7);
    }
}